<!-- 表格组件 -->
<template>
  <el-table ref="multipleTableRef" v-if="!tableData?.noRender" :data="myTable.list" :height="tableData.height" border
    size="large" v-loading="loading" class="my-table" @selection-change="onSelectionChange">
    <el-table-column type="selection" width="55" v-if="tableData.selection" />
    <el-table-column type="index" label="序号" width="65" v-if="tableData.index" align="center" />
    <el-table-column :prop="item.prop" :label="item.label" :width="item.width" :fixed="item.fixed"
      :show-overflow-tooltip="item.tooltip" :align="item.align" v-for="(item, index) in tableData.column">
      <template #default="scope" v-if="item.slot">
        <slot :slotData="scope.row" :slotColumn="item"></slot>
      </template>
    </el-table-column>
    <el-table-column :fixed="tableData?.columnBtn?.fixed" :label="tableData?.columnBtn?.label"
      :width="tableData?.columnBtn?.width" :align="tableData?.columnBtn?.align"
      v-if="tableData?.columnBtn?.btn && !tableData.noOperate">
      <template #default="scope">
        <span class="my-table__btn" v-for="(v, inx) in tableData?.columnBtn?.btn" @click="onClick(scope.row, v)">
          <span v-if="v.hide && v.hide(scope.row) || !v.hide" :style="{ color: v.color, borderColor: v.color }"
            class="t-table-btn">{{ v.text }}</span>
        </span>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <MyPagination v-if="!tableData?.noPage" :paginationDate="paginationDate" @listenPage="listenPage"
    @listenPageChange="listenPageChange">
  </MyPagination>
</template>
<script setup lang='ts'>
import { reactive, ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import http from '@/http/http'
import { FunApi } from '@/global/methods'

import { ElMessage, ElMessageBox } from 'element-plus'
import MyPagination from '@/components/MyPagination.vue'
import { ColumnBtnObj, ParentTable, PaginationDate } from '@/interface/index'
import { getSearchExtra, getSearchFamily } from '@/global/session'
let searchInfo = getSearchExtra()//搜索条件
let searchFamily = getSearchFamily()//家庭搜索条件
const store = useStore()
const router = useRouter()
const route = useRoute()
//监控加载状态
const loading = computed(() => {
  return store.getters['loading/getLoad']
})
//父传子 接口
interface PropsType {
  tableData: ParentTable
}
//分页
const paginationDate = reactive<PaginationDate>({
  pageSize: 10,//每页显示条目个数
  currentPage: 1,//当前页数
  total: 0,//总页数
  pageArr: [10, 20, 30, 40, 50]
})
if (searchInfo && route.path == '/extra/extraList') {
  let searchObj = JSON.parse(searchInfo)
  paginationDate.pageSize = searchObj.pageSize?searchObj.pageSize:10
  paginationDate.currentPage = searchObj.currentPage?searchObj.currentPage:1
}
if (searchFamily && route.path == '/family/familyList') {
  let searchObj = JSON.parse(searchFamily)
  paginationDate.pageSize = searchObj.pageSize?searchObj.pageSize:10
  paginationDate.currentPage = searchObj.currentPage?searchObj.currentPage:1
}

//父传子默认值
const props = withDefaults(defineProps<PropsType>(), {
  tableData: () => ({
    listApi: '',
    listHttp: '',
    column: []
  })
});
//子传父方法
const emit = defineEmits(['listenClick'])
//监听是否刷新表格 重新调接口
watch(
  () => store.getters['refresh/getRefresh'],
  () => {
    if (!props.tableData?.noPage) {//不隐藏分页  即有分页得时候
      paginationDate.currentPage = 1
    }
    onList()//获取列表
  }
)
//表格列表
const myTable = reactive({
  list: []
})
//获取列表
const onList = () => {
  let search = JSON.stringify(props.tableData.search)
  let params = JSON.parse(search)
  if (!props.tableData?.noPage) {//不隐藏分页  即有分页得时候
    params.pn = paginationDate.currentPage
    params.ps = paginationDate.pageSize
  }
  onListApi(params)
}
//列表搜索接口
const onListApi = async (params: any) => {
  if (props.tableData.listApi) {
    store.commit('loading/setLoad', true)
    try {
      let res = await http[props.tableData.listHttp](props.tableData.listApi, params)
      if (res?.code === 0) {
        if (!props.tableData?.noPage) {
          myTable.list = res.data.records
          paginationDate.total = res.data.total
        } else {
          myTable.list = res.data
        }
      }
      store.commit('loading/setLoad', false)
    } catch {
      store.commit('loading/setLoad', false)
    }
  }
}
//noRender没有或者false 就调用表格接口 渲染表格
if (!props.tableData?.noRender) {
  onList()
}
//表格操作 点击按钮
const onClick = (row: any, val: ColumnBtnObj) => {
  if (val.name === 'myApi' && val.api && val.http) {
    //如果是调接口
    if (val.confirm) {
      //需要二次确认
      onConfirm(row, val)
    } else {
      //不需要 直接调接口
      onApi(row, val)
    }
  } else if (val.name === 'myRouter') {
    //如果是跳转页面myRouter 走封装的跳转页面  
    //只传id 和  isLook （true则跳转的页面只能查看）  有其他传参的页面跳转抛给父级做 
    if (val.routerId) {
      router.push({ name: val.routerName, query: { id: row[val.routerId], isLook: val.isLook + '' } })
    } else {
      router.push({ name: val.routerName })
    }
  } else {
    //其他不走封装方法的 抛出去给父级 处理
    emit('listenClick', val.name, row)
  }
}
//二次确认弹窗
const onConfirm = (row: any, val: ColumnBtnObj) => {
  let confirmText = ''
  if (val.confirmText) {
    confirmText = row[val.confirmText]
  }
  store.commit('loading/setLoad', true)
  ElMessageBox.confirm(
    `请确定是否${val.text} ${confirmText} ?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }
  )
    .then(() => {
      //有接口掉接口 没有抛给父级
      if (val.http) {
        onApi(row, val)
      } else {
        emit('listenClick', val.name, row)
      }
    })
    .catch(() => {
      store.commit('loading/setLoad', false)
      ElMessage({ type: 'info', message: `取消${val.text}` })
    })
}
//掉接口
const onApi = async (row: any, val: ColumnBtnObj) => {
  let params = {}
  for (let key in val.params) {
    params[key] = params[key] ? params[key] : row[key]
  }
  let text = val.text
  //调接口公共方法
  FunApi(val.http, val.api!!, params, true, text, true)
}
//表格选中得内容
const multipleSelection = ref([])
//当选择项发生变化时会触发该事件
const onSelectionChange = (val: []) => {
  multipleSelection.value = val
  emit('listenClick', 'onSelectionChange', val)
}
//分页条数变化
const listenPage = (num: number) => {
  paginationDate.pageSize = num
  if (route.path == '/extra/extraList' || route.path == '/family/familyList') {
    emit('listenClick', 'onListenPageSize', num)
  }
  onList()
}
//页面切换
const listenPageChange = (num: number) => {
  paginationDate.currentPage = num
  if (route.path == '/extra/extraList' || route.path == '/family/familyList') {
    emit('listenClick', 'onListenPageIndex', num)
  }
  onList()
}
</script>
<style scoped lang='scss'>
.my-table {
  width: 100%;
  border: 1px solid #ebeef5;

  :deep(th.el-table__cell) {
    background: #f2f2f2;
    color: #111;
  }

  &__btn {
    >span {
      color: $my-color-primary;
      margin: 0 6px;
      cursor: pointer;

      &:hover {
        color: $my-color-info;
      }
    }
  }
}

.t-table-btn {
  line-height: 30px;
  padding: 0 15px;
  border-radius: 4px;
  border: 1px solid #3479D8;
  display: inline-block;
}
</style>